<template>
  <el-button
    :type="buttonType"
    :size="size"
    :loading="loading"
    :disabled="disabled"
    class="follow-button"
    :class="{ 'is-followed': isFollowed }"
    @click="handleClick"
  >
    <IconifyIconOffline :icon="buttonIcon" />
    {{ buttonText }}
  </el-button>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import { followUserApi } from "@/api/user-profile";

interface Props {
  userId: number;
  isFollowed: boolean;
  size?: "large" | "default" | "small";
  disabled?: boolean;
}

interface Emits {
  (e: "follow-change", isFollowed: boolean): void;
}

const props = withDefaults(defineProps<Props>(), {
  size: "default",
  disabled: false
});

const emit = defineEmits<Emits>();

// 响应式数据
const loading = ref(false);

// 计算属性
const buttonType = computed(() => {
  return props.isFollowed ? "default" : "primary";
});

const buttonIcon = computed(() => {
  return props.isFollowed ? "ep:check" : "ep:plus";
});

const buttonText = computed(() => {
  if (loading.value) {
    return props.isFollowed ? "取消关注中..." : "关注中...";
  }
  return props.isFollowed ? "已关注" : "关注";
});

// 方法
const handleClick = async () => {
  if (props.disabled || loading.value) return;

  try {
    loading.value = true;
    const newFollowState = !props.isFollowed;

    const response = await followUserApi({
      userId: props.userId,
      isFollow: newFollowState
    });

    if (response.code === 200) {
      emit("follow-change", newFollowState);
      ElMessage.success(newFollowState ? "关注成功" : "取消关注成功");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("关注操作失败:", error);
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.follow-button {
  transition: all 0.3s ease;

  &.is-followed {
    &:hover {
      color: #fff;
      background-color: #f56565;
      border-color: #f56565;

      :deep(.iconify) {
        transform: rotate(45deg);
      }
    }
  }

  :deep(.iconify) {
    margin-right: 4px;
    transition: transform 0.3s ease;
  }
}
</style>
